import React ,{useState,useEffect}from 'react';
import { Layout, Menu,Button, theme  } from 'antd';
const { Sider, Content } = Layout;
import { history ,Outlet,Navigate } from 'umi';
import {
  MenuFoldOutlined,
  MenuUnfoldOutlined,
  UploadOutlined,
  UserOutlined,
  VideoCameraOutlined,
  AppstoreOutlined,
  ContainerOutlined,
  DesktopOutlined,
  MailOutlined,
  PieChartOutlined,
} from '@ant-design/icons';
import { useNavigate, Routes, Route,matchRoutes } from 'react-router-dom'
import {iconList} from '@/utils/iconList'
import store from '@/redux/store.js'
import {setRouter} from '@/redux/actions/index.js'
import {getUser} from '@/utils/methods.ts'
import {menus} from '../../config/routes'
import Header from '@/components/Header'
import BreadCrumb from '@/components/BreadCrumb'
import './index.less'


function Layouts(props) {
  let routerData = store.getState().routerData
  const navigate = useNavigate();
  const [collapsed, setCollapsed] = useState(false);
  const [menuData,setMenuData] = useState([]);
  const [menuSelectKey,setMenuSelectKey] = useState([])
  const [menuOpenKeys, setMenuOpenKeys] = useState([]);
  // submenu keys of first level
  const [rootSubmenuKeys , setrootSubmenuKeys ] = useState([])
  // openKeys 当前展开的 SubMenu 菜单项 key 数组
  const [openKeys, setOpenKeys] = useState([]);
  let userInfo = JSON.parse(localStorage.getItem('userInfo'))
  useEffect(() => {
    const routes = matchRoutes(menus, location.pathname); // 返回匹配到的路由数组对象，每一个对象都是一个路由对象
    const pathArr = [];
    if (routes !== null) {
      routes.forEach((item) => {
        const path = item.path;
        if (path) {
          pathArr.push(path);
        }
      });
    }
    setMenuSelectKey(pathArr);
    setMenuOpenKeys(pathArr);
  }, [location.pathname]);
  const onOpenChange = (keys) => {
    const latestOpenKey = keys.find((key) => openKeys.indexOf(key) === -1);

    if (rootSubmenuKeys.indexOf(latestOpenKey) === -1) {
      setOpenKeys(keys);
    } else {
      setOpenKeys(latestOpenKey ? [latestOpenKey] : []);
    }
  };
  useEffect(()=>{
    let auth = userInfo.data.access
    let data = []
    let rootSubmenuKeys= []
    let allMenu = JSON.parse(JSON.stringify(menus))
    store.dispatch(setRouter(allMenu))
    menus.forEach((item)=>{
      //过滤权限菜单
      if(item.auths.includes(auth)){
        item['icon'] = iconList[item.key]
        rootSubmenuKeys.push(item.key)
        if(item.children){
          let childrenData = []
          item.children.forEach((child)=>{
            if(child.isShow){
              let eleData = []
              if(child.children != undefined && child.children.length>0){
                 child.children.forEach((ele)=>{
                   if(ele.isShow){
                     delete ele.isShow
                     eleData.push(ele)
                   }
                 })
              }
              if(eleData.length == 0){
                delete child.children
              }else{
                child.children = [...eleData]
              }
              delete child.isShow
              child['icon'] = iconList[child.key]
              childrenData.push(child)
            }
          })
          item.children = [...childrenData]
        }
        if(item.isShow != undefined){
          delete item.isShow
        }
        data.push(item)
      }
      setrootSubmenuKeys(rootSubmenuKeys)
    })
    setMenuData(data)
  },[])
  const menuClick = (e)=>{
    navigate(e.key)
    let currentRouter = []
    menuData.forEach((item)=>{
      if(item.children != undefined && item.children.length>0){
        item.children.forEach((ele)=>{
          if(ele.key == e.key){
            ele['current'] = true
          }else{
            ele['current'] = false
          }
        })
      }
      currentRouter.push(item)
    })
    // store.dispatch(setRouter(currentRouter))
    // history.push(e.key)
  }


  if(JSON.stringify(userInfo) == '{}'){
    return <Navigate to="/login" />;
  }else{
    return (
      <Layout className="pageMain">
        <Sider trigger={null} collapsible collapsed={collapsed} theme={"light"} className="layout-sider">
          <div className="logo-side">logo</div>
          <Menu
            mode="inline"
            defaultSelectedKeys={menuSelectKey}
            defaultOpenKeys={menuOpenKeys}
            style={{ height: '100%', borderRight: 0 }}
            items={menuData}
            onOpenChange={onOpenChange}
            onClick={menuClick}
          />
        </Sider>
        <Layout>
          <Header collapsed={collapsed} changeCollapsed={setCollapsed}/>
          <Content className="layout-con">
            <BreadCrumb/>
            <Outlet/>
          </Content>
        </Layout>
      </Layout>
    );
  }
}

export default Layouts;
